<template>
  <view class="container">
    <uni-forms :modelValue="detail" labelWidth="120px">
      <view class="form-title">{{ detail.title || '--' }}</view>
      <cu-cell-group style="margin-bottom: 20rpx">
        <uni-forms-item>
          <cu-cell title="报警时间">
            <view class="content">{{ detail.alarmTime || '--' }}</view>
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item>
          <cu-cell title="监测设备" v-if="detail.sourceType == 2">
            <view class="content">{{ detail.monitorDeviceName || '--' }}</view>
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item>
          <cu-cell title="报警位号" v-if="detail.sourceType == 2">
            <view class="content">{{ detail.positionNum || '--' }}</view>
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item>
          <cu-cell title="报警内容">
            <view class="content">{{ detail.content || '--' }}</view>
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item v-if="detail.classify === '31'">
          <cu-cell>
            <view class="flex-row-sb-c">
              <button class="btn" type="default" @click="goViewPositon(detail)">报警定位</button>
            </view>
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item v-if="detail.sourceType == 3">
          <cu-cell>
            <view class="flex-row-sb-c">
              <image-upload state="view" :imageUrl="detail.image"></image-upload>
              <button class="btn" type="default" @click="goViewMedia(detail.deviceId, detail.deviceName)">
                查看监控
              </button>
            </view>
          </cu-cell>
        </uni-forms-item>
      </cu-cell-group>
    </uni-forms>
    <uni-forms ref="formRef" :modelValue="formData" labelWidth="120px" labelPosition="top">
      <view class="form-title">处理反馈</view>
      <cu-cell-group style="margin-bottom: 240rpx">
        <uni-forms-item name="handlerResult">
          <cu-cell
            title="处理结果"
            required
            link
            placeholder="请选择处理结果"
            :description="formData.handlerResultLabel"
            @click="resultClick()"
          ></cu-cell>
        </uni-forms-item>
        <uni-forms-item name="reportDangerManager">
          <cu-cell title="上报隐患" required>
            <CuRadioGroup
              v-model="formData.reportDangerManager"
              :list="reportOptions"
              @change="changeReportDangerManager"
            />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item name="dangerManagerType" v-if="formData.reportDangerManager">
          <cu-cell
            title="隐患类型"
            required
            link
            placeholder="请选择隐患类型"
            :description="formData.dangerManagerTypeLabel"
            @click="managerTypeClick()"
          ></cu-cell>
        </uni-forms-item>
        <uni-forms-item name="dangerManagerLevel" v-if="formData.reportDangerManager">
          <cu-cell
            title="隐患级别"
            required
            link
            placeholder="请选择隐患级别"
            :description="formData.dangerManagerLevelLabel"
            @click="managerLevelClick()"
          ></cu-cell>
        </uni-forms-item>
        <uni-forms-item name="majorHiddenDangerType" v-if="formData.dangerManagerLevelLabel === '重大隐患'">
          <cu-cell
            title="重大隐患判定依据"
            required
            link
            placeholder="请选择重大隐患判定依据"
            :description="formData.majorHiddenDangerTypeLabel"
            @click="importantManagerClick()"
          ></cu-cell>
        </uni-forms-item>
        <uni-forms-item name="reason">
          <cu-cell title="报警原因" column>
            <textarea
              v-model="formData.reason"
              class="text-area"
              placeholder="请输入（100字）"
              placeholder-class="form-placeholder__style"
              maxlength="100"
            />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item name="measure">
          <cu-cell title="采取措施" column>
            <textarea
              v-model="formData.measure"
              class="text-area"
              placeholder="请输入（100字）"
              placeholder-class="form-placeholder__style"
              maxlength="100"
            />
          </cu-cell>
        </uni-forms-item>
        <uni-forms-item name="fileUrls" labelWidth="150">
          <cu-cell title="上传照片（最多3张）" column>
            <image-upload state="edit" :imageUrl="formData.fileUrls" @change="imageOnChange"> </image-upload>
          </cu-cell>
        </uni-forms-item>
      </cu-cell-group>

      <view class="submit-group">
        <button class="u-button margin-right-xs" type="primary" :ripple="true" @click="submit">提交</button>
        <button class="u-button-cancel margin-left-xs" type="default" :ripple="true" @click="navigateBack">取消</button>
      </view>
    </uni-forms>

    <dict-picker ref="resultDict" title="处理结果" dictType="ntf_alarm_info_result" @confirm="resultConfirm" />
    <dict-picker ref="managerTypeDict" title="隐患类型" dictType="dbd_manager_type" @confirm="managerTypeConfirm" />
    <dict-picker ref="managerLevelDict" title="隐患级别" dictType="dbd_manager_level" @confirm="managerLevelConfirm" />
    <manager-level-picker
      ref="importantManagerPicker"
      title="重大隐患判定依据"
      :data="managelList"
      @confirm="importantManagerConfirm"
    ></manager-level-picker>
  </view>
</template>

<script>
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import DictPicker from '@/components/dict-picker/index.vue'
import ImageUpload from '@/components/image-upload/index.vue'
import ManagerLevelPicker from '../components/ManagerLevelPicker.vue'
import { getWarnEventDetail, handleWarnEvent, reqGetPersonTrack } from '@/api/warn-event/index.js'
import { staticUrl } from '@/config.js'
import { getMajorHiddenDangerType } from '@/api/dbd/hiddenDangerReport.js'
import { encode } from '@/utils/js-base64.js'

export default {
  components: {
    CuCellGroup,
    CuCell,
    CuRadioGroup,
    DictPicker,
    ImageUpload,
    ManagerLevelPicker
  },
  data() {
    return {
      detail: {},
      managelList: [],
      reportOptions: [
        {
          label: '否',
          value: false
        },
        {
          label: '是',
          value: true
        }
      ],
      formData: {
        handlerResult: '', // 处理结果
        handlerResultLabel: '',
        reportDangerManager: '',
        dangerManagerType: '', //隐患类型
        dangerManagerTypeLabel: '',
        dangerManagerLevel: '', //隐患级别
        dangerManagerLevelLabel: '',
        majorHiddenDangerType: '', // 重大隐患判定依据
        majorHiddenDangerTypeLabel: '',
        reason: '', // 报警原因
        measure: '', // 采取措施
        fileUrls: '' // 照片
      },
      rules: {
        handlerResult: {
          rules: [
            {
              required: true,
              errorMessage: '处理结果不能为空'
            }
          ]
        },
        reportDangerManager: {
          rules: [
            {
              required: true,
              errorMessage: '上报隐患不能为空'
            }
          ]
        },
        dangerManagerType: {
          rules: [
            {
              required: true,
              errorMessage: '隐患类型不能为空'
            }
          ]
        },
        dangerManagerLevel: {
          rules: [
            {
              required: true,
              errorMessage: '隐患级别不能为空'
            }
          ]
        },
        majorHiddenDangerType: {
          rules: [
            {
              required: true,
              errorMessage: '重大隐患判定依据不能为空'
            }
          ]
        }
      }
    }
  },
  onLoad(option) {
    this.getDetail(option.id)
    this.getManagetList()
  },
  onReady() {
    this.$refs.formRef.setRules(this.rules)
  },
  methods: {
    getDetail(id) {
      getWarnEventDetail(id).then((res) => {
        this.detail = res.data || {}
      })
    },
    goViewPositon(detail) {
      let carCode = detail.carCode
      let alarmTime = detail.alarmTime
      let content = detail.content

      let username = content.substring(content.indexOf('【') + 1, content.indexOf('】'))
      if (!carCode || !alarmTime || !username) {
        this.$modal.showToast('无定位卡信息！')
        return
      }

      let startTime = new Date(alarmTime).getTime() - 5000
      let endTime = new Date(alarmTime).getTime() + 5000
      reqGetPersonTrack(carCode, { startTime, endTime }).then((res) => {
        if (res.length === 0 || !res[0].points.length === 0) {
          this.$modal.showToast('未查询到数据！')
          return
        }

        let point = res[0].points[0]
        let position = point.longitude + ',' + point.latitude
        let menuName = '人员定位'
        let routerPath = `${staticUrl}/sub-safety-production/cockpit/simple-position?type=person&cardId=${carCode}&userName=${username}&position=${position}`
        console.log(routerPath)
        let url = `/pages/work/report-form/query/view?title=${menuName}&url=${encodeURIComponent(routerPath)}`
        uni.navigateTo({
          url
        })
      })
    },
    goViewMedia(id, name) {
      uni.navigateTo({
        url: `/pages/work/warnEvent/viewMedia?id=${id}&name=${name}`
      })
    },
    // 处理结果
    resultClick() {
      this.$refs.resultDict.open()
    },
    resultConfirm({ name, value }) {
      this.formData.handlerResultLabel = name
      this.formData.handlerResult = value
    },
    // 上报隐患
    changeReportDangerManager() {
      this.formData.dangerManagerTypeLabel = ''
      this.formData.dangerManagerType = ''
      this.formData.dangerManagerLevelLabel = ''
      this.formData.dangerManagerLevel = ''
      this.formData.majorHiddenDangerTypeLabel = ''
      this.formData.majorHiddenDangerType = ''
    },
    // 隐患类型
    managerTypeClick() {
      this.$refs.managerTypeDict.open()
    },
    managerTypeConfirm({ name, value }) {
      console.log(name, value)
      this.formData.dangerManagerTypeLabel = name
      this.formData.dangerManagerType = value
    },
    // 隐患级别
    managerLevelClick() {
      this.$refs.managerLevelDict.open()
    },
    managerLevelConfirm({ name, value }) {
      this.formData.dangerManagerLevelLabel = name
      this.formData.dangerManagerLevel = value
      this.formData.majorHiddenDangerTypeLabel = ''
      this.formData.majorHiddenDangerType = ''
    },
    // 重大隐患判断依据
    getManagetList() {
      getMajorHiddenDangerType().then((res) => {
        this.managelList = res.data
      })
    },
    importantManagerClick() {
      this.$refs.importantManagerPicker.open()
    },
    importantManagerConfirm({ name, value }) {
      this.formData.majorHiddenDangerTypeLabel = name
      this.formData.majorHiddenDangerType = value
    },
    imageOnChange(urlList) {
      this.formData.fileUrls = urlList.join(',')
    },
    async submit() {
      await this.$refs.formRef.validate()
      const {
        handlerResult,
        reportDangerManager,
        dangerManagerType,
        dangerManagerLevel,
        majorHiddenDangerType,
        reason,
        measure,
        fileUrls
      } = this.formData
      if ((handlerResult === '2' && !reportDangerManager && !reason) || (reportDangerManager && !reason)) {
        uni.showToast({
          title: '报警原因不能为空',
          duration: 2000,
          icon: 'none'
        })
        return
      }
      const postData = {
        id: this.detail.id,
        handlerResult,
        reportDangerManager,
        dangerManagerType,
        dangerManagerLevel,
        majorHiddenDangerType,
        reason,
        measure,
        fileUrls: fileUrls ? fileUrls.split(',') : []
      }
      this.$modal.confirm('确定提交吗？').then(() => {
        handleWarnEvent(postData).then(() => {
          this.$modal.showToast('提交成功')
          this.navigateBack()
        })
      })
    },
    navigateBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  .form-title {
    background: #f5f5f5;
    padding: 20rpx;
    color: #333;
    font-size: 32rpx;
    font-weight: bold;
  }

  .content {
    font-size: 30rpx;
    word-break: break-all;
  }

  .warn-img {
    display: inline-block;
    width: 208rpx;
    height: 208rpx;
  }

  .btn {
    margin: 0;
    width: 220rpx;
    height: 70rpx;
    line-height: 70rpx;
    border-radius: 50rpx;
    background-color: #c4c088;
    color: #fff;
    font-size: 28rpx;
    margin-right: 10rpx;
  }

  .submit-group {
    background: #fff;
    z-index: 9;
    padding: 30px;
  }
}

::v-deep .cell-item__title {
  color: #999 !important;
}

::v-deep .cu-radio-group {
  align-items: center;
  justify-content: flex-end;

  > .cu-radio-item {
    padding-right: 0;
    margin-left: 60rpx;
  }
}
</style>
